<template>
  <div class="tree-item">
    <div class="tree-list-line" :style="{left:deep*20+'px'}" />
    <div v-if="deep>0" class="tree-point-line" :style="{left:deep*20+'px'}" />
    <div class="tree-title" :style="{paddingLeft:(20*deep+5)+'px'}" @click="toggle(tree)">
      <i v-if="tree.children" class="fa" :class="tree.isOpen?'fa-caret-down':'fa-caret-right'" />
      <slot :node="tree">
        <span class="fa" :class="tree.children?'fa-folder-o':'fa-file-text-o'" />
        <span class="tree-text">{{ tree.name }}</span>
      </slot>
      <span v-if="tree.loading" class="fa fa-spinner fa-pulse" />
    </div>
    <template v-if="tree.children&&tree.children.length>0">
      <div v-show="tree.isOpen" class="tree-list" :class="{'tree-list-open':tree.isOpen}">
        <TreeItem v-for="(item,i) in tree.children" :key="i" :tree="item" :deep="deep+1" @toggle-open="toggleOpen">
          <template slot-scope="{node}">
            <slot :node="node" />
          </template>
        </TreeItem>
      </div>
    </template>
  </div>
</template>

<script>
export default {
  name: 'TreeItem',
  props: {
    tree: {
      type: Object,
      default() {
        return {
          name: '文件夹',
          type: 'file'
        }
      }
    },
    deep: {
      type: Number,
      default: 0
    }
  },
  methods: {
    toggle(tree) {
      if (tree.isOpen === undefined) {
        this.$set(tree, 'isOpen', false)
      }
      tree.isOpen = !tree.isOpen
      this.$emit('toggle-open', tree)
    },
    toggleOpen(tree) {
      this.$emit('toggle-open', tree)
    }
  }
}
</script>

<style lang="less" scoped>
  .tree-item,.tree-list{
    position: relative;
  }
  .tree-item .tree-point-line{
    position: absolute;
    border-top: 1px dotted #333333;
    width: 10px;
    top: 15px;
    margin-left: -4px;
  }
  .tree-list-line{
    position: absolute;
    display: none;
    width: 1px;
    border-left: 1px dotted #333333;
    left: 10px;
    bottom: 0;
    top: 1px;
    z-index: 99;
    margin-left: -6px;
  }
  .tree-list-open>.tree-item>.tree-list-line{
    display: block;
  }
  .tree-list-open>.tree-item:first-child>.tree-list-line{
    top: -5px;
  }
  .tree-list-open>.tree-item:last-child>.tree-list-line{
    bottom: calc(100% - 16px);
  }
  .tree-item .tree-title{
    line-height: 30px;
    font-size: 14px;
    color: #666666;
    cursor: pointer;
  }
  .tree-item .tree-title>i:first-child{
    font-size: 20px;
    color: #a7a7a7;
    display: inline-block;
    width: 20px;
    text-align: center;
    margin-right: 3px;
    line-height: 30px;
  }
  .tree-item .tree-title span.fa:first-child{
    margin-left: 5px;
    margin-right: 3px;
  }
  .tree-item .tree-title .fa-spinner{
    position: absolute;
    right: 10px;
    top: 7px;
  }
  .tree-item .tree-title:hover{
    background-color: rgba(203, 225, 255, 0.3);
  }
</style>
